<template>
  <div>
    <div ref="editorRef"></div>
  </div>
</template>
<script lang="ts" setup>
import Quill from "quill";
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import { onMounted, ref, watch } from "vue";

interface Props {
  /**绑定值 */
  value: string;
  /**占位文本 */
  placeholder?: string;
}
const props = withDefaults(defineProps<Props>(), {
  placeholder: "请输入内容",
});
const emit = defineEmits(["update:value"]);
const editorRef = ref<HTMLElement>();
const quill = ref<Quill>();
onMounted(() => {
  quill.value = new Quill(editorRef.value, {
    placeholder: props.placeholder,
    modules: {
      toolbar: [
        [
          { header: [1, 2, 3, 4, 5, 6, false] },
          "bold",
          "italic",
          "underline",
          "strike",
          "color",
        ],
        ["blockquote", "code-block", "code"],
        ["link", "image", "video"],
      ],
    },
    theme: "snow",
  });
  if (props.value) {
    quill.value.root.innerHTML = props.value;
  }
  // 更新富文本值
  quill.value.root.addEventListener("blur", () => {
    emit("update:value", quill.value.getSemanticHTML());
  });
});
watch(
  () => props.value,
  async (value) => {
    if (quill.value) {
      quill.value.root.innerHTML = value;
    }
  }
);
</script>
